import 'dart:math';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:part_time_job_pro/common/models/books.dart';

import '../../common/db/sqflite_db_helper.dart';
import 'index.dart';

class SqliteController extends GetxController {
  final state = SqliteState();
  late final DatabaseHelper dbHelper;

  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    dbHelper = DatabaseHelper.instance;
    getAllBooks();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  ///插入数据进表
  Future<void> insertBooks() async {
    Map<String, dynamic> book = {
      'username': 'JohnDoe',
      'email': 'john.doe@example.com',
      'gender': 'Male',
      'birthday': '1990-01-01',
      'password': 'secure_password',
    };

    // 生成随机字符串
    String randomString = DateTime.now().millisecondsSinceEpoch.toString();
    //生成随机数
    int random = Random().nextInt(100);
    Books books = Books(
        bookName: 'The Great Gatsby $randomString',
        bookDesc: 'F. Scott Fitzgerald $randomString',
        createTime: DateTime.parse('2024-01-01'),
        isChecked: random % 2 == 0 ? true : false,
        bookNum: 20 + random);
    books = await dbHelper.insertBook(books);
    EasyLoading.showSuccess("增加数据成功!");
  }

  ///插入数据进表
  Future<void> updateBooks(Books books) async {
    int result = await dbHelper.updateBooksByEntity(books);
    if (result > 0) {
      EasyLoading.showSuccess('更新${books.bookId}成功');
    } else {
      EasyLoading.showError('更新${books.bookId}失败');
    }
  }

  ///所有数据
  Future<void> getAllBooks() async {
    List<Books> booksList = await dbHelper.queryAllBooks();
    print('All Books:');
    for (var book in booksList) {
      print(
          'id: ${book.bookId}, name: ${book.bookName}, num: ${book.bookNum}, bookDesc: ${book.bookDesc}, createTime: ${book.createTime}, isChecked: ${book.isChecked}');
    }
  }

  ///查找
  Future<void> getBooksInfo(int bookId) async {
    Books? book = await dbHelper.queryBooksById(bookId);
    if (book != null) {
      print(
          'get byID:$bookId ====>id: ${book.bookId}, name: ${book.bookName}, num: ${book.bookNum}, bookDesc: ${book.bookDesc}, createTime: ${book.createTime}, isChecked: ${book.isChecked}');
    }
  }

  ///删除
  Future<void> deleteBookdById(int bookId) async {
    int result = await dbHelper.deleteBookById(bookId);
    if (result > 0) {
      EasyLoading.showSuccess('删除$bookId成功');
    } else {
      EasyLoading.showError('删除$bookId失败');
    }
  }
}
